package com.mysteel.search.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.mysteel.common.to.es.SkuEsModel;
import com.mysteel.common.utils.R;
import com.mysteel.search.config.ElasticSearchConfig;
import com.mysteel.search.constant.EsConstant;
import com.mysteel.search.feign.ProductFeignService;
import com.mysteel.search.service.MailSearchService;
import com.mysteel.search.vo.AttrResponseVo;
import com.mysteel.search.vo.BrandEntityVo;
import com.mysteel.search.vo.SearchParams;
import com.mysteel.search.vo.SearchResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.TotalHits;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.util.UriUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ProjectName: mail
 * ClassName: MailSearchServiceImpl
 * Description:
 * date: 2021/01/28/028 19:39
 *
 * @author xiaochao
 */
@Service("mailSearchService")
public class MailSearchServiceImpl implements MailSearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private ProductFeignService productFeignService;

    @Override
    public SearchResult search(SearchParams params) {
        SearchResult searchResult = null;
        // 组装查询条件
        SearchRequest searchRequest = buildSearchRequest(params);
        try {
            // 执行查询请求
            SearchResponse response = restHighLevelClient.search(searchRequest, ElasticSearchConfig.COMMON_OPTIONS);
            // 分析响应数据，封装数据
            searchResult = buildSearchResult(response,params);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return searchResult;
    }

    /**
     * 组装查询返回结果
     * @param response
     * @return
     */
    private SearchResult buildSearchResult(SearchResponse response,SearchParams params) {
        SearchResult searchResult = new SearchResult();
        SearchHits hits = response.getHits();
        /**
         * 商品信息
         */
        SearchHit[] products = hits.getHits();
        if (products != null && products.length > 0){
            List<SkuEsModel> collect = Arrays.stream(products).map(product -> {
                String sourceAsString = product.getSourceAsString();
                SkuEsModel skuEsModel = JSONObject.parseObject(sourceAsString, SkuEsModel.class);
                // 设置高亮
                if (StringUtils.isNotEmpty(params.getKeyword())){
                    HighlightField skuTitleHighLight = product.getHighlightFields().get("skuTitle");
                    String skuTitle = skuTitleHighLight.getFragments()[0].string();
                    skuEsModel.setSkuTitle(skuTitle);
                }
                return skuEsModel;
            }).collect(Collectors.toList());
            searchResult.setProducts(collect);
        }
        /**
         * 分页信息
         */
        TotalHits totalHits = hits.getTotalHits();
        searchResult.setTotalCount(totalHits.value);
        Integer totalPage = (int) (totalHits.value % EsConstant.PRODUCT_PAGE_SIZE == 0 ? totalHits.value / EsConstant.PRODUCT_PAGE_SIZE : totalHits.value / EsConstant.PRODUCT_PAGE_SIZE + 1);
        searchResult.setTotalPage(totalPage);
        searchResult.setCurrentPageNum(params.getPageNum());
        ArrayList<Integer> pageNavs = new ArrayList<>(totalPage);
        for (int i = 1; i <= totalPage; i++){
            pageNavs.add(i);
        }
        searchResult.setPageNavs(pageNavs);
        /**
         * 查询结果涉及的所有品牌
         */
        ParsedLongTerms brandAgg = response.getAggregations().get("brandAgg");
        List<SearchResult.BrandVo> brandVos = brandAgg.getBuckets().stream().map(bucket -> {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            // 品牌Id
            brandVo.setBrandId(bucket.getKeyAsNumber().longValue());
            // 品牌图标
            ParsedStringTerms brandImgAgg = bucket.getAggregations().get("brandImgAgg");
            String brandImg = brandImgAgg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brandImg);
            // 品牌名称
            ParsedStringTerms brandNameAgg = bucket.getAggregations().get("brandNameAgg");
            String brandName = brandNameAgg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brandName);

            return brandVo;
        }).collect(Collectors.toList());
        searchResult.setBrands(brandVos);
        /**
         * 所有可筛选属性
         */
        ParsedNested attrAgg = response.getAggregations().get("attrAgg");
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attrIdAgg");
        List<SearchResult.AttrVo> attrVos = attrIdAgg.getBuckets().stream().map(bucket -> {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            // 属性Id
            Long attrId = bucket.getKeyAsNumber().longValue();
            attrVo.setAttrId(attrId);
            // 属性名称
            ParsedStringTerms attrNameAgg = bucket.getAggregations().get("attrNameAgg");
            String attrName = attrNameAgg.getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attrName);
            // 属性值
            ParsedStringTerms attrValueAgg = bucket.getAggregations().get("attrValueAgg");
            List<String> attrValues = attrValueAgg.getBuckets().stream().map(MultiBucketsAggregation.Bucket::getKeyAsString).collect(Collectors.toList());
            attrVo.setAttrValue(attrValues);
            return attrVo;
        }).collect(Collectors.toList());
        searchResult.setAttrs(attrVos);
        /**
         * 所有可筛选的分类信息
         */
        ParsedLongTerms catalogAgg = response.getAggregations().get("catalogAgg");
        List<SearchResult.CatalogVo> catalogVoList = catalogAgg.getBuckets().stream().map(bucket -> {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            // 品牌Id
            catalogVo.setCatalogId(Long.valueOf(bucket.getKeyAsString()));
            ParsedStringTerms catalogNameAgg = bucket.getAggregations().get("catalogNameAgg");
            // 品牌名称
            String catalogName = catalogNameAgg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalogName);
            return catalogVo;
        }).collect(Collectors.toList());
        searchResult.setCatalogs(catalogVoList);

        /**
         * 组装面包屑导航
         */
        if (!CollectionUtils.isEmpty(params.getAttrs())){
            ArrayList<Long> attrIds = new ArrayList<>();
            List<SearchResult.NavVo> collect = params.getAttrs().stream().map(attr -> {
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                String[] s = attr.split("_");
                R attrInfo = productFeignService.getAttrInfo(Long.valueOf(s[0]));
                if (attrInfo.getCode() == 0) {
                    AttrResponseVo attrResponseVo = attrInfo.getData("attr", new TypeReference<AttrResponseVo>() {
                    });
                    navVo.setNavName(attrResponseVo.getAttrName());
                } else {
                    navVo.setNavName(s[0]);
                }
                // 取消面包屑之后跳转链接，将请求地址的URL替换
                String encode = "";
                encode = UriUtils.encode(attr,"UTF-8");
                String replace = params.get_queryString().replace("&attrs=" + encode, "");
                navVo.setLinkUrl("http://search.xcmail.com/list.html?" + replace);
                navVo.setNavValue(s[1]);
                attrIds.add(Long.valueOf(s[0]));
                return navVo;
            }).collect(Collectors.toList());
            searchResult.setNavs(collect);
            searchResult.setAttrIds(attrIds);
        }

        if (!CollectionUtils.isEmpty(params.getBrandId())){
            List<SearchResult.NavVo> navs = searchResult.getNavs();
            SearchResult.NavVo navVo = new SearchResult.NavVo();
            navVo.setNavName("品牌");
            R brandInfos = productFeignService.getBrandInfos(params.getBrandId());
            if (brandInfos.getCode() == 0){
                List<BrandEntityVo> brands = brandInfos.getData("brands", new TypeReference<List<BrandEntityVo>>() {
                });
                StringBuffer sb = new StringBuffer();
                String linkUrl = params.get_queryString();
                for (BrandEntityVo brand : brands) {
                    sb.append(brand.getName()).append(";");
                    linkUrl = linkUrl.replace("brandId=" + brand.getBrandId(),"");
                }
                navVo.setNavValue(sb.toString());
                navVo.setLinkUrl("http://search.xcmail.com/list.html?" + linkUrl);
            }
            navs.add(navVo);
        }

        System.out.println(JSONObject.toJSONString(searchResult));

        return searchResult;
    }

    /**
     * 组装请求查询条件
     * @param params
     * @return
     */
    private SearchRequest buildSearchRequest(SearchParams params) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        /**
         * 查询（标题）、过滤（分类，品牌，属性，库存，价格）
         */
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        // must
        if (StringUtils.isNotEmpty(params.getKeyword())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle",params.getKeyword()));
        }
        // filter Catalog3Id
        if (params.getCatalog3Id() != null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId",params.getCatalog3Id()));
        }
        // filter brandId
        if (!CollectionUtils.isEmpty(params.getBrandId())){
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId",params.getBrandId()));
        }
        // filter attrs
        if (!CollectionUtils.isEmpty(params.getAttrs())){
            for (String attrStr : params.getAttrs()) {
                BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
                String[] s = attrStr.split("_");
                String attrId = s[0];
                String[] attrValues = s[1].split(":");
                boolQuery.must(QueryBuilders.termQuery("attrs.attrId",attrId));
                boolQuery.must(QueryBuilders.termsQuery("attrs.attrValue",attrValues));
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", boolQuery, ScoreMode.None);
                boolQueryBuilder.filter(nestedQuery);
            }

        }
        // filter hasStock
        if (params.getHasStock() != null){
            boolQueryBuilder.filter(QueryBuilders.termsQuery("hasStock", params.getHasStock() == 1));
        }
        // filter skuPrice 区间
        if (StringUtils.isNotEmpty(params.getSkuPrice())){
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] prices = params.getSkuPrice().split("_");
            if (prices.length == 2){
                rangeQuery.gte(prices[0]).lte(prices[1]);
            }else if (prices.length == 1){
                if (params.getSkuPrice().startsWith("_")){
                    rangeQuery.lte(prices[0]);
                }else {
                    rangeQuery.gte(prices[0]);
                }
            }
            boolQueryBuilder.filter(rangeQuery);
        }
        sourceBuilder.query(boolQueryBuilder);

        /**
         * 排序、分页、高亮
         */
        if (StringUtils.isNotEmpty(params.getSort())){
            String[] s = params.getSort().split("_");
            FieldSortBuilder sortBuilder = SortBuilders.fieldSort(s[0]).order("desc".equalsIgnoreCase(s[1]) ? SortOrder.DESC : SortOrder.ASC);
            sourceBuilder.sort(sortBuilder);
        }
        sourceBuilder.from((params.getPageNum() - 1) * EsConstant.PRODUCT_PAGE_SIZE);
        sourceBuilder.size(EsConstant.PRODUCT_PAGE_SIZE);
        if (StringUtils.isNotEmpty(params.getKeyword())){
            HighlightBuilder builder = new HighlightBuilder();
            builder.field("skuTitle");
            builder.preTags("<b style='color:red'>");
            builder.postTags("</b>");
            sourceBuilder.highlighter(builder);
        }

        /**
         * 聚合分析
         */
        // 品牌聚合
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brandAgg");
        TermsAggregationBuilder brandNameAgg = AggregationBuilders.terms("brandNameAgg").field("brandName").size(1);
        TermsAggregationBuilder brandImgAgg = AggregationBuilders.terms("brandImgAgg").field("brandImg").size(1);
        brandAgg.field("brandId").size(50).subAggregation(brandNameAgg).subAggregation(brandImgAgg);
        sourceBuilder.aggregation(brandAgg);
        // 分类聚合
        TermsAggregationBuilder catalogAgg = AggregationBuilders.terms("catalogAgg").field("catalogId").size(20);
        catalogAgg.subAggregation(AggregationBuilders.terms("catalogNameAgg").field("catalogName").size(1));
        sourceBuilder.aggregation(catalogAgg);
        // 属性聚合
        NestedAggregationBuilder nestedAggregation = AggregationBuilders.nested("attrAgg", "attrs");
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attrIdAgg").field("attrs.attrId").size(100);
        attrIdAgg.subAggregation(AggregationBuilders.terms("attrNameAgg").field("attrs.attrName").size(1));
        attrIdAgg.subAggregation(AggregationBuilders.terms("attrValueAgg").field("attrs.attrValue").size(50));
        nestedAggregation.subAggregation(attrIdAgg);
        sourceBuilder.aggregation(nestedAggregation);

        System.out.println(sourceBuilder.toString());

        return new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX},sourceBuilder);
    }
}
